/**
 * @IOHandler.java  COPYRIGHT xiaojian
 * 
 * Created on 2017年7月12日 下午2:12:41
 */
package xj.toolkit.access;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import xiaojian.toolkit.bean.CommonsHeader;
import xj.toolkit.access.AccessHeader;
import xj.toolkit.access.AccessMsgCodeConstants;
import xj.toolkit.access.msg.AccessAckMessage;
import xj.toolkit.access.msg.AccessContentMessage;
import xj.toolkit.access.msg.AccessSynMessage;

/**
 * @author <a href="mailto:cxj2000@gmail.com">xiaojian.cao</a>
 *
 */
@ChannelHandler.Sharable
public class IOHandler extends ChannelInboundHandlerAdapter {

	private static final Logger logger = LoggerFactory.getLogger(IOHandler.class);


	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.debug("receive msg[{}].", msg);
		
		CommonsHeader commonsHeader = new CommonsHeader();
		commonsHeader.setType(CommonsHeader.RESPONSE);
		
		commonsHeader.setMessageLength(AccessHeader.HEADER_LENGTH);
		
		AccessHeader header  = new AccessHeader();
		header.setSourceInstanceId((short)0);
		header.setSourceModuleId((short)2);
		
		if (msg instanceof AccessSynMessage) {
			commonsHeader.setMessageCode(AccessMsgCodeConstants.MSG_CODE_ACK);
			
			AccessSynMessage syn = (AccessSynMessage) msg;
			
			header.setTargetModuleId(syn.getAccessHeader().getSourceModuleId());
			header.setTargetModuleId(syn.getAccessHeader().getTargetModuleId());
			
			AccessAckMessage ackMessage = new AccessAckMessage();
			ackMessage.setAccessHeader(header);
			ackMessage.setCommonHeader(commonsHeader);
			
			ctx.channel().writeAndFlush(ackMessage);
			
			logger.debug("send resp->" + ackMessage);
			
			return;
		}
		
		AccessContentMessage contentMsg = (AccessContentMessage) msg;
		
		commonsHeader.setMessageCode(contentMsg.getCommonHeader().getMessageCode() + 1);
		header.setTargetModuleId(contentMsg.getAccessHeader().getSourceModuleId());
		header.setTargetModuleId(contentMsg.getAccessHeader().getTargetModuleId());
		
		AccessContentMessage resp = new AccessContentMessage();
		resp.setAccessHeader(header);
		resp.setCommonHeader(commonsHeader);
		resp.setContent(contentMsg.getContent());
		
		ctx.channel().writeAndFlush(resp);
		
		logger.debug("send resp->" + resp);
		
	}
}
